//
//  HomeTableViewController.swift
//  ZHTQWeibo
//
//  Created by ZHTQ on 2018/9/13.
//  Copyright © 2018年 ZHTQ. All rights reserved.
//

import UIKit

class HomeTableViewController: BaseTableViewController {

    /// 微博数据处理
    var statusListModel: StatusListModel = StatusListModel()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        if !isLogin
        {
            // 设置访客视图
            visitorView?.setupVisitorInfo(nil, title: "关注一些人，回这里看看有什么惊喜")
            return
        }
        
        //2.初始化导航条
        setUpNavigationBar()
        
        //3.注册通知
        NotificationCenter.default.addObserver(self, selector: #selector(titleButtonChange), name: NSNotification.Name(PresentationPresentedNotification), object: presentationManager)
        NotificationCenter.default.addObserver(self, selector: #selector(titleButtonChange), name: NSNotification.Name(PresentationDismissNotification), object: presentationManager)
        
        NotificationCenter.default.addObserver(self, selector: #selector(intoBrowserViewController(notification:)), name: NSNotification.Name(ZHTQCollectionCellSelectedNotification), object: nil)
        // 4.加载微博数据
        loadStatus()
        
        tableView.estimatedRowHeight = 400
        tableView.separatorStyle = UITableViewCellSeparatorStyle.none
//        tableView.rowHeight = UITableViewAutomaticDimension
        
        // 下拉刷新控件
        refreshControl = HomeRefreshControl()
        refreshControl?.addTarget(self, action: #selector(loadStatus), for: UIControlEvents.valueChanged)
        refreshControl?.beginRefreshing()
        
        // 添加显示拉刷新的微博条数
        navigationController?.navigationBar.insertSubview(reminedLable, at: 0)
    }

    //MARK:- 内部方法
    
    /// 加载微博数据 statuses   
    @objc private func loadStatus() {
        
        statusListModel.loadStatus(isLastStatus: isLastStatus) { (statusesVM, error) in
            
            if error != nil {
                ZHLog("数据请求错误")
                
                self.refreshControl?.endRefreshing()
                self.reminedStatusCount(count: 0)
                return
            }
            
            self.tableView.reloadData()

            // 取消下拉刷新
            self.refreshControl?.endRefreshing()
            
            // 显示下拉数据条数的动画
            self.reminedStatusCount(count: statusesVM!.count)
        }
    }
    
    private func reminedStatusCount(count: Int) {
        reminedLable.isHidden = false
        reminedLable.text = count == 0 ? "没有更多微博数据" : "加载了\(count)条微博数据"
        
        // 动画
        UIView.animate(withDuration: 0.5, animations: {
            self.reminedLable.transform = CGAffineTransform(translationX: 0, y: 44)
        }) { (_) in
            
            UIView.animate(withDuration: 0.5, delay: 1.5, options: UIViewAnimationOptions(rawValue: 0), animations: {
                self.reminedLable.transform = CGAffineTransform.identity
            }, completion: { (_) in
                self.reminedLable.isHidden = true
            })
        }
    }
    
    ///监听通知
    @objc private func titleButtonChange() {
        titleBtn.isSelected = !titleBtn.isSelected
    }
    
    /// 点击微博图片跳转到图片浏览界面
    @objc private func intoBrowserViewController(notification: NSNotification) {
        // 安全校验
        guard let bmiddles = notification.userInfo!["bmiddle_urls"] as? [URL] else {
            return
        }
        
        guard let indexpath = notification.userInfo!["indexpath"] as? IndexPath else {
            return
        }
        
        // 跳转到微博图片浏览界面
        present(BrowserViewController(bmiddle_urls: bmiddles, indexpath: indexpath), animated: true, completion: nil)
    }
    
    ///初始化导航条
    private func setUpNavigationBar(){
        //1.创建导航条左边右边的按钮 添加按钮监听
        navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendattention", target: self, action: #selector(leftButtonClick))
        navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop", target: self, action: #selector(rightButtonClick))
        
        //2.设置导航条文字按钮 添加按钮监听
        titleBtn.addTarget(self, action: #selector(titleButtonClick(btn:)), for: UIControlEvents.touchUpInside)
        navigationItem.titleView = titleBtn
    }
    
    /// 监听标题按钮点击
    @objc private func titleButtonClick(btn: TitleButton) {
        //2.显示modal菜单试图
        //2.1创建modal 控制器
        let sb = UIStoryboard(name: "Popover", bundle: nil)
        
        guard let vc = sb.instantiateInitialViewController() else {
            ZHLog("控制器获取失败")
            return
        }
        
        //设置转场代理
        vc.transitioningDelegate = presentationManager
        vc.modalPresentationStyle = UIModalPresentationStyle.custom
        
        //2.2弹出控制器
        present(vc, animated: true, completion: nil)
    }
    
    ///监听左边按钮点击
    @objc private func leftButtonClick() {
        if  UserAccount.deleteUserAccount() {
        }
    }
    
    ///监听扫一扫按钮点击
    @objc private func rightButtonClick() {
        let sb = UIStoryboard(name: "QRCode", bundle: nil)
        guard let QRVC = sb.instantiateInitialViewController() else {
            return
        }
        present(QRVC, animated: true, completion: nil)
    }
    
    
    
    //MARK:- 懒加载
    /// 显示下拉刷新了几条微博
    private lazy var reminedLable: UILabel = { () -> (UILabel) in
       let lb = UILabel(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 44))
        lb.backgroundColor = UIColor.orange
        lb.textAlignment = NSTextAlignment.center
        lb.text = "没有更多微博数据"
        lb.isHidden = true
        return lb
    }()
    
    /// 转场的管理
    private lazy var presentationManager: ZHTQPresentationManager = {
        let width: CGFloat = 200
        let x: CGFloat = (UIScreen.main.bounds.width - width)  / 2
        
        //设置显示的试图的大小
        let manager = ZHTQPresentationManager()
        manager.presentedViewFrame = CGRect(x: x, y: 54, width: width, height: width)
        return manager
    }()
    
    /// 标题按钮
    private lazy var titleBtn = { () -> TitleButton in
        let Btn = TitleButton()
        let title = UserAccount.loadUserAccount()?.screen_name
        Btn.setTitle(title, for: UIControlState.normal)
        return Btn
    }()
    
    /// 缓存行高
    private var cachedHeight = [String: CGFloat]()
    
    /// 是否是最后一条微博
    private var isLastStatus = false
}


extension HomeTableViewController {
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        let a = statusListModel.statuses?.count ?? 0
        return a
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        // 判断是否是转发微博
        let statusVM = statusListModel.statuses?[indexPath.row]
        let identifier = statusVM?.status?.retweeted_status != nil ?  "forwardCell" : "homeCell"
        
        let cell = tableView.dequeueReusableCell(withIdentifier: identifier, for: indexPath) as! HomeTableViewCell
        cell.statusViewModel = statusVM
        
        // 判断是否是最后一条微博
        isLastStatus = false
        if indexPath.row == statusListModel.statuses!.count - 3  {
            ZHLog("最后三条微博")
            ZHLog(statusVM?.status?.user?.screen_name)
            
            isLastStatus = true
            
            loadStatus()
        }
        
        return cell
    }
    
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        guard let cachedH = cachedHeight[(statusListModel.statuses![indexPath.row].status?.idstr)!] else {
        
            // 判断是否是转发微博
            let statusVM = statusListModel.statuses?[indexPath.row]
            let identifier = statusVM?.status?.retweeted_status != nil ?  "forwardCell" : "homeCell"

            
            // 获取当前的cell
            let cell = tableView.dequeueReusableCell(withIdentifier: identifier) as! HomeTableViewCell
            let height = cell.cellHeight(statusViewModel: statusListModel.statuses![indexPath.row])
            cachedHeight[(statusListModel.statuses![indexPath.row].status?.idstr)!] = height
            
            
            return height
        }
        
        return cachedH
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        cachedHeight.removeAll()
    }
}



